/*
 * @Descripttion:
 * @version: 1.0.0
 * @Author: liuzicheng
 * @Date: 2025-01-23 09:20:30
 * @LastEditors: liuzicheng
 * @LastEditTime: 2025-02-25 15:54:07
 */
import tabsStore from "@/store/tabsStore";
import userStore from "@/store/userStore";
import { IRoute, IRoutePageConfig } from "@/vite-env";
import { Spin } from "antd";
import { lazy, Suspense } from "react";
import KeepAlive from "react-activation";
const modules = import.meta.glob(["@/pages/**/index.tsx", "!@/pages/**/components/**/index.tsx"], {});
const pagesConfig = import.meta.glob("@/pages/**/page.ts", { eager: true });
// 包装懒加载组件
const wrapSuspense = (Component: React.ComponentType, isKeepAlive: boolean, cacheKey: string) =>
  isKeepAlive ? (
    <KeepAlive when={true} cacheKey={cacheKey} id={cacheKey} name={cacheKey}>
      <Suspense fallback={<Spin />}>
        <Component />
      </Suspense>
    </KeepAlive>
  ) : (
    <Suspense fallback={<Spin />}>
      <Component />
    </Suspense>
  );
// console.log(modules, pagesConfig, "modules")
const genAccessRoutes = (key: keyof typeof pagesConfig = "", isParent: boolean = false) => {
  const pathKey = key.replace(/\/page.ts$/, "/index.tsx");
  const path = key.replace(/\/page.ts$/, "").replace(/\/src\/pages/, "");

  const pageContent = pagesConfig[key] as { default: IRoutePageConfig };
  const con = JSON.parse(JSON.stringify(pageContent.default));
  delete con.name;
  delete con.icon;
  const Com = lazy(modules[pathKey] as any);
  const routeObj: any = {
    path,
    name: pageContent.default.name,
    meta: con,
    icon: pageContent.default.icon
  };
  if (isParent) {
    routeObj.children = [];
  } else {
    routeObj.element = wrapSuspense(Com, con?.keepalive, path);
  }

  return routeObj;
};
const findParent = (parentRoutes: IRoute[], sonRoute: IRoute) => {
  parentRoutes.forEach((item) => {
    if (item.path === sonRoute.meta?.parentPath) {
      item.children?.push({ ...sonRoute });
    } else if (item.children?.length) {
      findParent(item.children, sonRoute);
    }
  });
};
const staticRoutesIsRoles = (role) => {
  if (!role) return true;
  return role?.some((item) => userStore.roles?.includes(item));
};

const handleParentRoutes = () => {
  const parentRoutes: IRoute[] = [];
  const sonRoutes: IRoute[] = [];
  Object.keys(pagesConfig).map((key) => {
    const pageConfig = pagesConfig[key] as { default: IRoutePageConfig };
    const content = pageConfig?.default;
    if (!content.parentPath?.trim() && staticRoutesIsRoles(content.roles)) {
      const router = genAccessRoutes(key, content?.isHasChild);
      parentRoutes.push(router);
      if (content?.fixed) {
        tabsStore.visitedViewsTabs.unshift(router);
      }
    } else if (staticRoutesIsRoles(content.roles)) {
      sonRoutes.push(genAccessRoutes(key));
    }
  });
  const pRoutes = sortOrderRoute(parentRoutes);
  const sRoutes = sortOrderRoute(sonRoutes);
  return { parentRoutes: pRoutes, sonRoutes: sRoutes };
};
const sortOrderRoute = (routes: IRoute[]) => {
  routes?.sort((a, b) => {
    return a.meta?.order - b.meta?.order;
  });
  return routes;
};
function formatUrl(url) {
  return url.replace(/([^:])\/\//g, "$1/"); // 只替换协议后的多余 `//`
}
const getAsyncRoutes = () => {
  return userStore.menuList?.map((item) => {
    const Com = lazy(modules[formatUrl(`/src/pages/${item.path}/index.tsx`)] as any);
    return {
      ...item,
      element: wrapSuspense(Com, item.meta?.keepalive, item?.path)
    };
  });
};
const handleTreeRoutes = () => {
  const { parentRoutes, sonRoutes } = handleParentRoutes();
  sonRoutes.forEach((item) => {
    findParent(parentRoutes, item);
  });
  userStore.setMenus();
  const asyncRoutes = getAsyncRoutes();
  return [...parentRoutes, ...asyncRoutes];
};
const treeRouter = handleTreeRoutes();
export default treeRouter;
